package cn.chencq.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 网关拦截器
 * 
 * @author chencq
 * @email chenchaoqun@incar100.com
 * @date 2018-3-13 上午11:18:43
 */
public class GateWayInterceptor implements HandlerInterceptor {

	private static final Logger LOG = LoggerFactory
			.getLogger(GateWayInterceptor.class);

	private static ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>(
			"StartTime-ThreadLocal");

	/**
	 * 
	 * 预处理
	 */

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		startTimeThreadLocal.set(System.currentTimeMillis());
		return true;
	}

	/**
	 * 
	 * 返回处理
	 */

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 
	 * 后处理
	 */

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		try {
			long costTime = System.currentTimeMillis() - startTimeThreadLocal.get();
			LOG.info("costTime:{}ms", costTime);
		} finally {
			startTimeThreadLocal.remove();// 清除数据
		}
	}

}
